<?php

class DoctrineValidatorPollLog extends sfValidatorBase
{
  public function configure($option = array(), $message = array())
  {
    $this->addOption('ip');
    
    $this->addMessage('ip', '一天只能投票一次，您今天已经投过票了。');
  }

  protected function doClean($value)
  {
    $ip = empty($_SERVER['HTTP_CLIENT_IP']) 
      ? (empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['REMOTE_ADDR'] : $_SERVER['HTTP_X_FORWARDED_FOR'])
      : $_SERVER['HTTP_CLIENT_IP'];

    $account = Doctrine::getTable('PollLog')->createQuery('p')
      ->where('ip = ?', ip2long($ip))
      ->andWhere('created_at > ?', date('Y-m-d 00:00:00'))
      ->andWhere('created_at < ?', date('Y-m-d 00:00:00', time() + 86400))
      ->limit(1)
      ->execute();

    if ($account[0]->getId()||ip2long($ip)==0)
    {
      throw new sfValidatorError($this, 'ip');
    }

    else
    {
      $pollLog = new PollLog();
      $pollLog->setContestantId($value['contestant_id'])
        ->setIp(ip2long($ip))
        ->save();
        
      $contestant = $pollLog->getContestant();
      $contestant->setHits($contestant->getHits() + 1)
        ->save();
    }

    return $value;
  }
}
